layui.config({
    base: '/plugins/module/'
});

layui.use(['form', 'step', 'layer', 'laydate', 'upload', 'cstmodules'], function () {
    var $ = layui.$,
        form = layui.form,
        step = layui.step,
        layer = layui.layer,
        laydate = layui.laydate,
        mymod = layui.cstmodules,
        upload = layui.upload;

    var gradeid = 0;       //  证书类型子id
    var addCentType = "";  //  证书详细信息1
    var globalgrade = 0;   //  证书分数
    var special;           //  存储有计算公式的返回数据
    var certificate_image;        //  证书图片名字
    var certificate_type = 0;     //  证书类型父id
    var scoreformula = "";       // 计算公式
    var addCentTypes = [];
    var stompClient = null;

    //日期
    laydate.render({
        elem: '#date'
    });
    laydate.render({
        elem: '#date1'
    });

    var cstmgr = {
        select: function (data, number) {
            var select = $("#select-div" + number);
            if (select.length > 0) {
                var content = "<label class='layui-form-label'>" + data[0].category + ":</label>";
                content += "<div class='layui-input-block'>";
                content += "<select lay-verify='required' name='select" + number + "' lay-select lay-filter='aihao" + number + "'>";
                content += "<option value=''>请选择" + data[0].category + "</option>";
                for (var i = 0; i < data.length; i++) {
                    content += "<option value='" + data[i].id + "'>" + data[i].name + "</option>";
                }
                content += "</select>";
                content += "<div id='grade" + number + "'></div>";
                content += "</div>";
                $("#select-div" + number).html(content);
                form.render();
            }
        },
        s: function (productid, number) {
            $.ajax(
                {
                    url: "/jf/s/jfConfSonInfo",
                    data: {"productid": productid},
                    type: "post",
                    dataType: "json",
                    success: function (data) {
                        if (data.code == 1) {
                            cstmgr.select(data.listObj, number);
                        } else if (data.code == 2) {
                            var gradeList = data.listObj[0];
                            gradeid = productid;
                            var gradenumber = $("#grade" + (number - 1));
                            if (gradenumber.length > 0) {
                                globalgrade = gradeList.grade;
                                var content = "<spen style = 'color='#FFF';&nbsp;'>*</spen><spen>当前选择的分数或加分规则为：" + gradeList.grade + "分</spen>";
                                $("#grade" + (number - 1)).html(content);
                                scoreformula = null;
                                form.render();
                            }
                        } else if (data.code == 3) {

                            var grade = data.listObj[0];
                            gradeid = productid;
                            var gradenumber = $("#grade" + (number - 1));
                            if (gradenumber.length > 0) {
                                scoreformula = grade.scoreformula;
                                var content = "<spen style = 'color='#FFF';&nbsp;'>*</spen><spen>当前选择的分数或加分规则为：" + grade.scoreformula + "分</spen>";
                                $("#grade" + (number - 1)).html(content);
                                special = grade;
                                globalgrade = 0;
                                cstmgr.am(special);

                                var content1 = "<div></div>";
                                $("#dynamic").html(content1);
                                form.render();
                            }
                        } else {
                            layer.alert(data.msg);
                        }
                    },
                    error: function () {
                        layer.alert("异常");
                    }
                });
        },
        am: function (special) {
            var select = $("#amount");
            if (select.length > 0) {
                var content = "<div class='ayui-form-item'>";
                content += "<label class='layui-form-label'>" + special.remark + ":</label>";
                content += "<div class='layui-input-block'>";
                content += "<input type='number' name='numerical_interval' id='numerical_interval' placeholder='请填写" + special.remark + "' value='' class='layui-input' lay-verify='number' required>";
                content += "</div>";
                content += "</div>";
                $("#amount").html(content);
                $("#judge").val(1);
                form.render();
            }
        },
        deletselect: function (number) {
            for (var j = number; j < 6; j++) {
                var select = $("#select-div" + j);
                if (select.length > 0) {
                    var content = "<div></div>";
                    $("#select-div" + j).html(content);
                    form.render();
                }
            }
        },
        deletgrade: function (number) {
            for (var j = number; j < 6; j++) {
                var select = $("#grade" + j);
                if (select.length > 0) {
                    var content = "<div></div>";
                    $("#grade" + j).html(content);
                    form.render();
                }
            }
        },
        error: function () {
            layer.alert("异常");
        },
        uploading: function (field) {
            var data = mymod.callBackMethod("/jf/i/jfDetailCertificateInfo", "post", field);
            if (data.code == 1) {
                //send（）是一个计算机函数，功能是向一个已经连接的socket发送数据，如果无错误，返回值为所发送数据的总数，否则返回SOCKET_ERROR。
                console.log("向一个已经连接的socket发送数据:");
                //send（）是一个计算机函数，功能是向一个已经连接的socket发送数据，如果无错误，返回值为所发送数据的总数，否则返回SOCKET_ERROR。
                stompClient.send("/app/user", {}, JSON.stringify({'name': 1}));

                var select = $("#RI");
                if (select.length > 0) {
                    var content = "<i class='layui-icon layui-circle' style='color: white;font-size:30px;font-weight:bold;background: #52C41A;padding: 20px;line-height: 80px;'>&#xe605;</i>";
                    content += "<div style='font-size: 24px;color: #333;font-weight: 500;margin-top: 30px;' id='result'>上传成功</div>";
                    $("#RI").html(content);
                    form.render();
                }
            } else {
                console.log(data.code);
                var select = $("#RI");
                if (select.length > 0) {
                    var content = "<i class='layui-icon layui-circle' style='color: white;font-size:30px;font-weight:bold;background: #c00;padding: 20px;line-height: 80px;' >&#x1006;</i>";
                    content += "<div style='font-size: 24px;color: #333;font-weight: 500;margin-top: 30px;' id='result'>上传失败</div>";
                    $("#RI").html(content);
                    form.render();
                }
            }

            //关闭SockJS的双通道
            if (stompClient !== null) {
                stompClient.disconnect();
            }
            // setConnected(false);
            console.log("Disconnected");
        },
        addCentTypesupdet: function () {
            addCentType = "";
            $("#pluscontent").html("");
            form.render();

            for (var i = 1; i < 6; i++) {
                if (addCentTypes[i] != null) {
                    addCentType = addCentType + addCentTypes[i];
                }
            }

            var x;
            if (scoreformula != "") {
                x = addCentType + "-分数或加分规则为：" + scoreformula + "分";
            }
            if (globalgrade != 0) {
                x = addCentType + "-分数或加分规则为：" + globalgrade + "分";
            }

            console.log(x);
            $("#pluscontent").html(x);
            $("#detailed_information").val(addCentType);
            $("#certificate_type_name").val(addCentTypes[1]);
            $("#grade").val(globalgrade);
            $("#certificate_type_pid").val(gradeid);
            $("#certificate_type").val(certificate_type);
            $("#scoreformula").val(scoreformula);
        },
        //SockJS的一大好处在于提供了浏览器兼容性。即优先使用原生WebSocket，如果浏览器不支持WebSocket，会自动降为轮询的方式。
        connects: function () {
            var socket = new SockJS('/websocket-demo');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function (frame) {
                // setConnected(true);
                console.log('Connected: ' + frame);//连接服务器成功
            });
        }
    }

    step.render({
        elem: '#stepForm',
        filter: 'stepForm',
        stepItems: [{
            title: '选择加分信息'
        }, {
            title: '填写详细信息'
        }, {
            title: '完成'
        }]
    });

    $.ajax(
        {
            url: "/jf/f/jfConfFatherInfo",
            data: "",
            type: "post",
            dataType: "json",
            success: function (data) {
                if (data.code == 1) {
                    cstmgr.select(data.listObj, 1);
                } else {
                    layer.alert(data.msg);
                }
            }
        });

    cstmgr.connects();

    form.on('select(aihao1)', function (data) {
        var productid = data.value;
        if (productid === "" || productid < 1) {
            return;
        }
        certificate_type = productid;
        addCentTypes[1] = data.elem[data.elem.selectedIndex].text;
        cstmgr.s(productid, 2);
        cstmgr.deletselect(2);
        cstmgr.deletgrade(1);
    });

    form.on('select(aihao2)', function (data) {
        var productid = data.value;
        if (productid === "" || productid < 1) {
            return;
        }
        addCentTypes[2] = "-" + data.elem[data.elem.selectedIndex].text;
        cstmgr.s(productid, 3);
        cstmgr.deletselect(3);
        cstmgr.deletgrade(2);
    });

    form.on('select(aihao3)', function (data) {
        var productid = data.value;
        if (productid === "" || productid < 1) {
            return;
        }
        addCentTypes[3] = "-" + data.elem[data.elem.selectedIndex].text;
        cstmgr.s(productid, 4);
        cstmgr.deletselect(4);
        cstmgr.deletgrade(3);
    });

    form.on('select(aihao4)', function (data) {
        var productid = data.value;
        if (productid === "" || productid < 1) {
            return;
        }
        addCentTypes[4] = "-" + data.elem[data.elem.selectedIndex].text;
        cstmgr.s(productid, 5);
    });

    form.on('select(aihao5)', function (data) {
        var productid = data.value;
        if (productid === "" || productid < 1) {
            return;
        }
        addCentTypes[5] = "-" + data.elem[data.elem.selectedIndex].text;
        cstmgr.s(productid, 6);
    });

    form.on('submit(formStep)', function (data) {
        data = data.field;
        if (data.select == '') {
            layer.msg('加分类型不能为空');
            return false;
        }

        cstmgr.addCentTypesupdet();

        step.next('#stepForm');
        return false;
    });

    //自定义验证规则
    form.verify({
        title: function (value) {
            if (value.length <= 0) {
                return '请输入证书名称';
            }
        }, certificate_image: function (value) {
            if (value.length <= 0) {
                return '请上传图片';
            }
        }
    });

    //普通图片上传
    var uploadInst = upload.render({
        elem: '#test1'
        , url: '/upload/file/' //改成您自己的上传接口
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#demo1').attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.code != 1) {
                return layer.msg('上传失败');
            }
            //上传成功
            certificate_image = res.info;

            $("#imageUte").removeClass("add",1);
            $("#certificate_image").val(certificate_image);
        }
        , error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });

    form.on('submit(formStep2)', function (data) {
        cstmgr.uploading(data.field);
        step.next('#stepForm');
        return false;
    });

    form.on('submit(formStep3)', function (data) {
        window.location.reload();
    });

    $('.pre').click(function () {
        step.pre('#stepForm');
    });

    $('.next').click(function () {
        step.next('#stepForm');
    });
})